package cn.kgm.makeGod;

import cn.kgm.makeGod.condition.WorldState;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 资源抢夺与战斗系统
 */
public class ResourceCompetitionSystem {

    // 资源类型及其价值
    public static final Map<Integer, Integer> RESOURCE_VALUES = new HashMap<>();

    static {
        RESOURCE_VALUES.put(1, 1000); // 万年蛇胎酒
        RESOURCE_VALUES.put(2, 200);  // 高级丹药
        RESOURCE_VALUES.put(3, 50);   // 灵草
        RESOURCE_VALUES.put(4, 800);  // 上古法宝
        RESOURCE_VALUES.put(5, 300);  // 珍稀材料
    }

    /**
     * 通用资源抢夺方法
     *
     * @param world      世界状态
     * @param resourceId 资源ID
     * @param location   资源所在位置
     * @param characters 参与抢夺的角色列表
     * @return 抢夺胜利者的ID，如果没有胜利者返回-1
     */
    public static int competeForResource(WorldState world, int resourceId, Location location, List<Character> characters) {
        if (characters.isEmpty()) {
            return -1;
        }
        // 如果只有一个角色留下，直接获得资源
        if (characters.size() == 1) {
            Character winner = characters.get(0);
            System.out.println(winner.getName() + " 捡了大漏，获得了资源!");
            world.acquireItem(winner.getId(), resourceId, 1);
            return winner.getId();
        }
        // 土遁符检查
        WorldState.competeForResourceWithEscapeCheck(world, resourceId, location, characters);

        System.out.println("在" + location.getName() + "，多个角色开始争夺" +
                world.getItem(resourceId).getName() + "!");

        // 按战斗力排序角色
        List<Character> sortedCharacters = new ArrayList<>(characters);
        sortedCharacters.sort((c1, c2) ->
                Integer.compare(calculateCombatPower(c2), calculateCombatPower(c1)));

        // 最强大的角色有最高概率获胜
        Character strongest = sortedCharacters.get(0);
        int victoryChance = 70; // 最强角色70%概率获胜

        Random random = new Random();
        if (random.nextInt(100) < victoryChance) {
            // 最强角色获胜
            resolveResourceAcquisition(world, strongest, resourceId, characters);
            return strongest.getId();
        } else {
            // 随机选择一个其他角色获胜（模拟意外）
            int randomIndex = random.nextInt(sortedCharacters.size() - 1) + 1;
            Character winner = sortedCharacters.get(randomIndex);
            resolveResourceAcquisition(world, winner, resourceId, characters);
            return winner.getId();
        }
    }

    /**
     * 处理资源获取和关系变化
     */
    private static void resolveResourceAcquisition(WorldState world, Character winner,
                                                   int resourceId, List<Character> competitors) {
        Item item = world.getItem(resourceId);
        System.out.println(winner.getName() + " 成功获得了 " + item.getName() + "!");

        // 获胜者获得物品
        world.acquireItem(winner.getId(), resourceId, 1);

        // 处理失败者的反应
        for (Character loser : competitors) {
            if (loser.getId() != winner.getId()) {
                // 关系恶化
                int relationshipChange = -10 - (RESOURCE_VALUES.getOrDefault(resourceId, 100) / 100);
                adjustRelationship(loser, winner, relationshipChange);

                System.out.println(loser.getName() + " 对 " + winner.getName() +
                        " 的关系值减少了 " + (-relationshipChange));

                // 根据性格决定是否发起战斗
                if (shouldInitiateBattle(loser, winner, resourceId)) {
                    initiateBattle(world, loser, winner, resourceId);
                }
            }
        }
    }

    /**
     * 判断是否发起战斗
     */
    private static boolean shouldInitiateBattle(Character aggressor, Character target, int resourceId) {
        // 基础战斗概率
        int baseChance = 30;

        // 性格影响
        if (aggressor.hasPersonality(PersonalityTag.GRUDGE, 60)) {
            baseChance += 20; // 记仇的人更容易发起战斗
        }
        if (aggressor.hasPersonality(PersonalityTag.EVIL, 50)) {
            baseChance += 15; // 邪恶的人更容易发起战斗
        }
        if (aggressor.hasPersonality(PersonalityTag.KIND, 70)) {
            baseChance -= 20; // 善良的人不太可能发起战斗
        }

        // 资源价值影响
        int resourceValue = RESOURCE_VALUES.getOrDefault(resourceId, 100);
        baseChance += resourceValue / 50; // 价值越高，越可能战斗

        // 战斗力差距影响
        int powerDifference = calculateCombatPower(aggressor) - calculateCombatPower(target);
        if (powerDifference > 0) {
            baseChance += 10; // 比自己弱的更可能攻击
        } else {
            baseChance -= 15; // 比自己强的不太可能攻击
        }

        Random random = new Random();
        return random.nextInt(100) < Math.max(5, Math.min(90, baseChance));
    }

    /**
     * 发起战斗
     */
    public static BattleResult initiateBattle(WorldState world, Character attacker, Character defender, int resourceId) {
        System.out.println(attacker.getName() + " 对 " + defender.getName() + " 发起了战斗!");
        if (checkEscapeBeforeBattle(world, defender, attacker)) {
            System.out.println(defender.getName() + " 使用土遁符逃脱了战斗!");
            return BattleResult.FLEE;
        }
        // 计算战斗力
        int attackerPower = calculateCombatPower(attacker);
        int defenderPower = calculateCombatPower(defender);

        // 加入随机因素
        Random random = new Random();
        attackerPower += random.nextInt((attacker.getLuck() <= 1 ? 2 : attacker.getLuck()) / 2);
        defenderPower += random.nextInt((defender.getLuck() <= 1 ? 2 : defender.getLuck()) / 2);

        // 决定战斗结果
        BattleResult result;
        if (attackerPower > defenderPower * 1.5) {
            result = BattleResult.VICTORY;
            resolveBattleVictory(world, attacker, defender, resourceId);
        } else if (defenderPower > attackerPower * 1.5) {
            result = BattleResult.DEFEAT;
            resolveBattleDefeat(world, attacker, defender, resourceId);
        } else {
            result = BattleResult.DRAW;
            resolveBattleDraw(world, attacker, defender, resourceId);
        }

        // 处理战斗后的关系变化
        handlePostBattleRelationships(attacker, defender, result);

        return result;
    }

    /**
     * 处理战斗胜利
     */
    private static void resolveBattleVictory(WorldState world, Character winner, Character loser, int resourceId) {
        System.out.println(winner.getName() + " 战胜了 " + loser.getName() + "!");

        // 胜利者可能夺取资源
        if (world.getItemsOwnedBy(loser.getId()).stream()
                .anyMatch(io -> io.getItemId() == resourceId)) {
            // 转移资源
            world.transferItem(loser.getId(), winner.getId(), resourceId, 1);
            System.out.println(winner.getName() + " 从 " + loser.getName() + " 手中夺走了资源!");
        }

        // 失败者受伤
        int damage = calculateCombatPower(winner) / 10;
        loser.setCurrentHp(loser.getCurrentHp() - damage);
        System.out.println(loser.getName() + " 受到了 " + damage + " 点伤害");

        // 如果生命值过低，可能死亡
        if (loser.getCurrentHp() <= 0) {
            handleCharacterDeath(world, loser, winner);
        }
    }

    /**
     * 处理战斗失败
     */
    private static void resolveBattleDefeat(WorldState world, Character loser, Character winner, int resourceId) {
        System.out.println(loser.getName() + " 被 " + winner.getName() + " 击败了!");

        // 失败者受伤
        int damage = calculateCombatPower(winner) / 8;
        loser.setCurrentHp(loser.getCurrentHp() - damage);
        System.out.println(loser.getName() + " 受到了 " + damage + " 点伤害");

        // 如果生命值过低，可能死亡
        if (loser.getCurrentHp() <= 0) {
            handleCharacterDeath(world, loser, winner);
        }
    }

    /**
     * 检查并使用土遁符
     *
     * @param world    世界状态
     * @param user     使用土遁符的角色
     * @param opponent 对手角色
     * @return 是否成功使用土遁符逃脱
     */
    public static boolean useEarthEscapeTalisman(WorldState world, Character user, Character opponent) {
        // 检查用户是否拥有土遁符
        List<ItemOwnership> talismans = world.getItemsOwnedBy(user.getId()).stream()
                .filter(io -> io.getItemId() == 7 || io.getItemId() == 8) // 土遁符或高级土遁符
                .collect(Collectors.toList());

        if (talismans.isEmpty()) {
            return false; // 没有土遁符
        }

        // 选择最好的土遁符（优先使用高级的）
        ItemOwnership bestTalisman = talismans.stream()
                .max(Comparator.comparingInt(io -> io.getItemId())) // ID越大越高级
                .orElse(null);

        if (bestTalisman == null) {
            return false;
        }

        EarthEscapeTalisman talisman = (EarthEscapeTalisman) world.getItem(bestTalisman.getItemId());

        // 计算实力差距
        int userPower = calculateCombatPower(user);
        int opponentPower = calculateCombatPower(opponent);
        int powerDifference = opponentPower - userPower;

        // 计算逃脱概率
        int escapeChance = calculateEscapeChance(talisman, powerDifference);

        Random random = new Random();
        if (random.nextInt(100) < escapeChance) {
            // 逃脱成功
            System.out.println(user.getName() + " 使用了 " + talisman.getName() + "，成功逃脱!");

            // 传送到安全地点
            Location safeLocation = findSafeLocation(world, user.getCurrentLocation(), talisman.getEscapeDistance());
            user.setCurrentLocation(safeLocation);
            System.out.println(user.getName() + " 土遁到了 " + safeLocation.getName());

            // 消耗土遁符
            world.useItem(user.getId(), bestTalisman.getItemId());

            // 关系变化：对手可能会看不起逃跑者
            adjustRelationship(opponent, user, -10);

            return true;
        } else {
            // 逃脱失败
            System.out.println(user.getName() + " 使用了 " + talisman.getName() + "，但逃脱失败!");

            // 消耗土遁符
            world.useItem(user.getId(), bestTalisman.getItemId());

            // 关系变化：对手可能会嘲笑逃跑者
            adjustRelationship(opponent, user, -5);

            return false;
        }
    }

    // ... 之前的代码 ...

    /**
     * 计算逃脱概率
     */
    private static int calculateEscapeChance(EarthEscapeTalisman talisman, int powerDifference) {
        int baseChance = talisman.getEscapeChanceBase();

        // 实力差距影响：差距越大，逃脱概率越低
        if (powerDifference > 0) {
            // 每10点实力差距降低1%逃脱概率，最多降低30%
            int penalty = Math.min(30, powerDifference / 10);
            baseChance -= penalty;
        } else {
            // 如果比对手强，逃脱概率增加
            int bonus = Math.min(20, -powerDifference / 15);
            baseChance += bonus;
        }

        // 确保概率在5%到95%之间
        return Math.max(5, Math.min(95, baseChance));
    }

    /**
     * 寻找安全地点
     */
    private static Location findSafeLocation(WorldState world, Location currentLocation, int maxDistance) {
        List<Location> allLocations = new ArrayList<>(world.getLocations().values());
        Collections.shuffle(allLocations);

        // 优先选择与当前位置不同类型的地点
        for (Location location : allLocations) {
            if (!location.equals(currentLocation) &&
                    location.getType() != currentLocation.getType()) {
                return location;
            }
        }

        // 如果没有不同类型的地点，随机选择一个
        return allLocations.stream()
                .filter(l -> !l.equals(currentLocation))
                .findFirst()
                .orElse(currentLocation); // 如果只有一个地点，返回原地
    }

    /**
     * 在战斗前检查土遁符使用
     */
    public static boolean checkEscapeBeforeBattle(WorldState world, Character potentialFleeer, Character opponent) {
        // 计算实力差距
        int userPower = calculateCombatPower(potentialFleeer);
        int opponentPower = calculateCombatPower(opponent);
        int powerDifference = opponentPower - userPower;

        // 如果对手明显更强，考虑使用土遁符
        if (powerDifference > 20) {
            // 检查是否有土遁符
            List<ItemOwnership> talismans = world.getItemsOwnedBy(potentialFleeer.getId()).stream()
                    .filter(io -> io.getItemId() == 7 || io.getItemId() == 8)
                    .collect(Collectors.toList());

            if (!talismans.isEmpty()) {
                // 根据性格决定是否使用土遁符
                if (shouldUseTalisman(potentialFleeer, powerDifference)) {
                    return useEarthEscapeTalisman(world, potentialFleeer, opponent);
                }
            }
        }

        return false;
    }

    /**
     * 判断是否使用土遁符
     */
    public static boolean shouldUseTalisman(Character character, int powerDifference) {
        int baseChance = 50; // 基础使用概率

        // 性格影响
        if (character.hasPersonality(PersonalityTag.GRUDGE, 60)) {
            baseChance -= 20; // 记仇的人不太可能逃跑
        }
        if (character.hasPersonality(PersonalityTag.ARROGANT, 60)) {
            baseChance -= 25; // 傲慢的人不太可能逃跑
        }
        if (character.hasPersonality(PersonalityTag.EVIL, 50)) {
            baseChance += 10; // 邪恶的人更可能逃跑
        }
        if (character.hasPersonality(PersonalityTag.SELFISH, 50)) {
            baseChance += 15; // 自私的人更可能逃跑
        }
        if (character.hasPersonality(PersonalityTag.KIND, 60)) {
            baseChance += 5; // 善良的人可能选择逃跑避免冲突
        }

        // 实力差距影响：差距越大，越可能使用
        baseChance += Math.min(30, powerDifference / 5);

        Random random = new Random();
        return random.nextInt(100) < Math.max(10, Math.min(90, baseChance));
    }

    /**
     * 扩展的战斗发起方法，加入土遁符检查
     */
    public static BattleResult initiateBattleWithEscapeCheck(WorldState world, Character attacker, Character defender, int resourceId) {
        // 检查防守方是否使用土遁符逃跑
        if (checkEscapeBeforeBattle(world, defender, attacker)) {
            System.out.println(defender.getName() + " 在战斗开始前使用土遁符逃脱了!");
            return BattleResult.FLEE;
        }

        // 如果没有逃跑，正常进行战斗
        return initiateBattle(world, attacker, defender, resourceId);
    }

    /**
     * 处理平局
     */
    private static void resolveBattleDraw(WorldState world, Character attacker, Character defender, int resourceId) {
        System.out.println(attacker.getName() + " 和 " + defender.getName() + " 的战斗以平局收场!");

        // 双方都受伤
        int attackerDamage = calculateCombatPower(defender) / 15;
        int defenderDamage = calculateCombatPower(attacker) / 15;

        attacker.setCurrentHp(attacker.getCurrentHp() - attackerDamage);
        defender.setCurrentHp(defender.getCurrentHp() - defenderDamage);

        System.out.println(attacker.getName() + " 受到了 " + attackerDamage + " 点伤害");
        System.out.println(defender.getName() + " 受到了 " + defenderDamage + " 点伤害");
    }

    /**
     * 处理角色死亡
     */
    private static void handleCharacterDeath(WorldState world, Character deceased, Character killer) {
        System.out.println(deceased.getName() + " 不幸陨落!");

        // 移除角色
        world.getCharacters().remove(deceased.getId());

        // 处理死亡角色的物品
        List<ItemOwnership> deceasedItems = world.getItemsOwnedBy(deceased.getId());
        if (!deceasedItems.isEmpty() && killer != null) {
            // 杀手获得部分物品
            Random random = new Random();
            for (ItemOwnership item : deceasedItems) {
                if (random.nextInt(100) < 70) { // 70%概率获得每件物品
                    world.transferItem(deceased.getId(), killer.getId(), item.getItemId(), item.getQuantity());
                    System.out.println(killer.getName() + " 获得了 " + deceased.getName() + " 的 " +
                            world.getItem(item.getItemId()).getName());
                }
            }
        }

        // 通知与死者有关系的角色
        for (Character character : world.getCharacters().values()) {
            Relationship rel = character.getRelationshipTo(deceased.getId());
            if (rel != null && rel.getValue() > 0) {
                System.out.println(character.getName() + " 得知 " + deceased.getName() + " 的死讯，悲痛欲绝");

                // 如果知道凶手，关系恶化
                if (killer != null) {
                    adjustRelationship(character, killer, -40);
                }
            }
        }
    }

    /**
     * 处理战斗后的关系变化
     */
    private static void handlePostBattleRelationships(Character attacker, Character defender, BattleResult result) {
        switch (result) {
            case VICTORY:
                adjustRelationship(attacker, defender, -30); // 胜者对败者更加轻视
                adjustRelationship(defender, attacker, -50); // 败者对胜者更加仇恨
                break;
            case DEFEAT:
                adjustRelationship(attacker, defender, -40); // 败者对胜者更加仇恨
                adjustRelationship(defender, attacker, -20); // 胜者对败者稍微轻视
                break;
            case DRAW:
                adjustRelationship(attacker, defender, -25); // 平局双方关系恶化
                adjustRelationship(defender, attacker, -25);
                break;
        }
    }

    /**
     * 调整角色关系
     */
    private static void adjustRelationship(Character source, Character target, int change) {
        Relationship rel = source.getRelationshipTo(target.getId());
        if (rel != null) {
            int newValue = Math.max(-100, Math.min(100, rel.getValue() + change));
            rel.setValue(newValue);

            // 根据新值更新关系类型
            if (newValue >= 80) rel.setType(RelationshipType.LOVER);
            else if (newValue >= 50) rel.setType(RelationshipType.FRIEND);
            else if (newValue <= -50) rel.setType(RelationshipType.SWORN_ENEMY);
            else rel.setType(RelationshipType.STRANGER);
        } else {
            RelationshipType type = change > 0 ? RelationshipType.FRIEND : RelationshipType.STRANGER;
            if (change <= -50) type = RelationshipType.SWORN_ENEMY;

            source.addRelationship(new Relationship(
                    source.getId(), target.getId(), type, change
            ));
        }
    }

    /**
     * 计算角色战斗力
     */
    public static int calculateCombatPower(Character character) {
        return character.getLevel() * 5 +
                character.getAttack() * 2 +
                character.getDefense() +
                character.getLuck() / 3;
    }

    /**
     * 检查位置上的资源争抢
     */
    public static void checkResourceCompetition(WorldState world, Location location) {
        // 获取该位置的所有角色
        List<Character> charactersAtLocation = new ArrayList<>();
        for (Character character : world.getCharacters().values()) {
            if (character.getCurrentLocation().getId() == location.getId()) {
                charactersAtLocation.add(character);
            }
        }

        if (charactersAtLocation.size() < 2) {
            return; // 至少需要两个角色才能争抢
        }

        // 检查该位置是否有可用资源
        for (ResourceNode node : world.getResourceNodes().values()) {
            if (node.getLocation().getId() == location.getId() && node.isAvailable()) {
                // 触发资源争抢
                int winnerId = competeForResource(world, node.getItemId(), location, charactersAtLocation);

                // 如果确定了胜利者，标记资源为已采集
                if (winnerId != -1) {
                    node.harvest();
                }

                break; // 一次只处理一个资源点
            }
        }
    }

    // 战斗结果枚举
    public enum BattleResult {
        VICTORY, DEFEAT, DRAW, FLEE
    }
}
